package com.wzy.service.impl;

import com.wzy.entity.Province;
import com.wzy.mapper.ProvinceMapper;
import com.wzy.service.ProvinceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.util.Const;
import com.wzy.util.Pager;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类，
 * </p>
 *
 * @author wzy
 * @since 2021-02-09
 */
@Service
public class ProvinceServiceImpl extends ServiceImpl<ProvinceMapper, Province> implements ProvinceService {

    @Resource
    private ProvinceMapper provinceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int append(Province province) {
        Set<String> keys = redisTemplate.keys("*provinces*");
        redisTemplate.delete(keys);
        return this.provinceMapper.inserts(province);
    }

    @Override
    public int updateProvince(Long provinceId, Province province) throws NotFoundException {
        Set<String> keys = redisTemplate.keys("*provinces*");
        redisTemplate.delete(keys);
        Province p = provinceMapper.selectById(provinceId);
        if (p == null) {
            throw new NotFoundException("不存在该类型");
        }
        provinceMapper.delete(provinceId);
        BeanUtils.copyProperties(province, p); //将province里面的值赋值给p
        return provinceMapper.inserts(p);

    }

    @Override
    public int modifyProvinceName(Long provinceId, String provinceName) {
        Set<String> keys = redisTemplate.keys("*provinces*");
        redisTemplate.delete(keys);
        Province province = new Province();
        province.setProvinceId(provinceId);
        province.setProvinceName(provinceName);
        return this.provinceMapper.inserts(province);
    }

    @Override
    public Province getProvinceByName(String provinceName) {
        return this.provinceMapper.selectByName(provinceName);
    }

    @Override
    public boolean remove(Long provinceId) {
        Set<String> keys = redisTemplate.keys("*provinces*");
        redisTemplate.delete(keys);
        return this.provinceMapper.delete(provinceId);
    }

    @Override
    public Province detail(Long provinceId) {
        return this.provinceMapper.selectById(provinceId);
    }

    @Override
    public Pager<Province> list(Integer page) {
        List<Province> datas = this.provinceMapper.list((page - 1) * Const.PAGE_SIZE, Const.PAGE_SIZE);
        int size = this.provinceMapper.size();
        return new Pager<>(datas, size, page, Const.PAGE_SIZE);
    }

    @Override
    public List<Province> list() {
        return this.provinceMapper.list(0, 0);
    }


}
